const time = {}

function getToady () {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const today = `${year}/${month}/${day}`
  return new Date(today).getTime() // 当天凌晨的时间
}

function isToday (time) {
  const todayTime = getToady() // 当天凌晨的时间
  // const yesterdayTime = new Date(todayTime - 24 * 60 * 60 * 1000).getTime() // 昨天凌晨的时间
  return time > todayTime
}

function isYesterday (time) {
  const todayTime = getToady() // 当天凌晨的时间
  const yesterdayTime = new Date(todayTime - 24 * 60 * 60 * 1000).getTime() // 昨天凌晨的时间
  return time < todayTime && yesterdayTime <= time
}

function isLastYesterday (time) {
  const twentyFourHours = 24 * 60 * 60 * 1000
  const fortyEightHours = 24 * 60 * 60 * 1000 * 2
  const todayTime = getToady() // 当天凌晨的时间
  const yesterdayTime = new Date(todayTime - twentyFourHours).getTime() // 昨天凌晨的时间
  const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime() // 昨天凌晨的时间
  return time < yesterdayTime && lastYesterdayTime <= time
}

/**
 * @description 格式化消息的时间
 * @param {String} name cookie name
 */
time.formatSendTime = function (time) {
  let afterT = time.split('T')[1].split(':')
  let timestamp = new Date(time).getTime()
  const offset = (new Date()).getTimezoneOffset()
  timestamp = timestamp + offset * 60000
  let result = ''
  if (isToday(timestamp)) {
    result = '今天 '
  } else if (isYesterday(timestamp)) {
    result = '昨天 '
  } else if (isLastYesterday(timestamp)) {
    result = '前天 '
  } else {
    result = time.split('T')[0] + ' '
  }
  result = result + afterT[0] + ':' + afterT[1]
  return result
}

time.localTime = function (time) {
  const d = new Date(time || Date.now())
  d.setMinutes(d.getMinutes() - d.getTimezoneOffset())
  return d.toISOString()
}

export default time
